<template>
  <div class="page-content">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3 flex items-center">
        <router-link to="/" class="mr-2">
          <i class="fas fa-arrow-left text-gray-600"></i>
        </router-link>
        <h1 class="text-lg font-semibold">诉讼费计算</h1>
      </div>
    </header>

    <main class="container mx-auto px-4 mt-4">
      <div class="bg-white rounded-xl shadow-md p-6">
        <h2 class="text-lg font-semibold mb-4">诉讼费计算器</h2>
        <p class="text-sm text-gray-500 mb-6">
          根据不同案件类型和标的金额计算应缴纳的诉讼费用，计算结果仅供参考
        </p>

        <!-- 案件类型选择 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-3">
            <i class="fas fa-gavel mr-1"></i>
            请选择案件类型
            </label>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            <div 
              v-for="type in caseTypeOptions" 
              :key="type.value"
              class="relative"
            >
              <input
                v-model="caseType"
                :id="type.value"
                type="radio"
                :value="type.value"
                class="sr-only"
                @change="onCaseTypeChange"
              />
              <label
                :for="type.value"
                class="flex flex-col items-center justify-center p-4 border-2 rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                :class="caseType === type.value 
                  ? 'border-blue-500 bg-blue-50 shadow-md' 
                  : 'border-gray-200 hover:border-blue-300'"
              >
                <i :class="type.icon" class="text-2xl mb-2" :class="caseType === type.value ? 'text-blue-600' : 'text-gray-400'"></i>
                <span class="text-sm font-medium text-center" :class="caseType === type.value ? 'text-blue-900' : 'text-gray-700'">
                  {{ type.label }}
                </span>
                <span class="text-xs text-gray-500 text-center mt-1">
                  {{ type.description }}
                </span>
              </label>
            </div>
          </div>
        </div>

        <!-- 案件参数配置区域 -->
        <div v-if="caseType" class="mb-6 p-4 bg-gray-50 rounded-lg">
          <h3 class="text-md font-medium text-gray-800 mb-4 flex items-center">
            <i class="fas fa-cog mr-2"></i>
            {{ getCaseTypeLabel(caseType) }}参数配置
          </h3>

          <!-- 请求赔偿金额输入（始终显示，非必填） -->
          <div class="p-4 bg-blue-50 rounded-lg border border-blue-200">
            <label class="block text-sm font-semibold text-blue-800 mb-2">
              <i class="fas fa-money-bill-wave mr-1"></i>
              请求赔偿金额（元）<span class="text-xs text-gray-500 ml-1">（非必填）</span>
            </label>
            <div class="relative">
            <input
              v-model.number="claimAmount"
              type="number"
                min="0"
                step="0.01"
                placeholder="请输入赔偿金额（可选）"
                class="w-full p-3 pr-12 border border-blue-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
              />
              <span class="absolute right-3 top-3 text-gray-500">元</span>
            </div>
            <div class="mt-2 text-xs text-blue-600">
              <p>• 此字段为可选项，不填写不影响计算</p>
              <p>• 填写后可获得更精确的费用计算</p>
              <p v-if="claimAmount && claimAmount > 0" class="mt-1 font-medium">当前金额：{{ formatAmount(claimAmount) }}</p>
            </div>
          </div>

          <!-- 审理程序和审级（通用配置） -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-200">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
                <i class="fas fa-fast-forward mr-1"></i>
                审理程序
              </label>
              <div class="space-y-2">
                <label class="flex items-center p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors" 
                       :class="{ 'border-blue-500 bg-blue-50': procedureType === 'ordinary' }">
                  <input v-model="procedureType" type="radio" value="ordinary" class="mr-2" />
                  <span class="text-sm">普通程序</span>
                </label>
                <label class="flex items-center p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
                       :class="{ 'border-blue-500 bg-blue-50': procedureType === 'simple' }">
                  <input v-model="procedureType" type="radio" value="simple" class="mr-2" />
                  <span class="text-sm">简易程序（减半收费）</span>
                </label>
                <label v-if="canUseSummaryProcedure" class="flex items-center p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
                       :class="{ 'border-blue-500 bg-blue-50': procedureType === 'summary' }">
                  <input v-model="procedureType" type="radio" value="summary" class="mr-2" />
                  <span class="text-sm">小额诉讼（最高500元）</span>
                </label>
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">
                <i class="fas fa-building mr-1"></i>
                审级
              </label>
              <div class="space-y-2">
                <label class="flex items-center p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
                       :class="{ 'border-blue-500 bg-blue-50': courtLevel === 'first' }">
                  <input v-model="courtLevel" type="radio" value="first" class="mr-2" />
                  <span class="text-sm">一审</span>
                </label>
                <label class="flex items-center p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
                       :class="{ 'border-blue-500 bg-blue-50': courtLevel === 'second' }">
                  <input v-model="courtLevel" type="radio" value="second" class="mr-2" />
                  <span class="text-sm">二审（按一审1.5倍收费）</span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 验证提示 -->
        <div v-if="!canCalculate && caseType" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <p class="text-sm text-red-700 font-medium mb-2">
            <i class="fas fa-exclamation-circle mr-1"></i>
            请完善以下信息：
          </p>
          <ul class="text-sm text-red-600 space-y-1">
            <li v-for="error in getValidationErrors()" :key="error" class="flex items-center">
              <i class="fas fa-dot-circle mr-2 text-xs"></i>
              {{ error }}
            </li>
          </ul>
        </div>

        <!-- 实时计算提示 -->
        <div v-if="canCalculate" class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
          <p class="text-sm text-green-700">
            <i class="fas fa-check-circle mr-1"></i>
            参数已就绪，点击下方按钮进行详细计算
          </p>
        </div>

        <!-- 计算按钮 -->
        <button
          @click="calculateFee"
          class="w-full py-3 px-4 rounded-lg font-medium transition-all duration-200"
          :class="canCalculate 
            ? 'bg-blue-600 hover:bg-blue-700 text-white shadow-md hover:shadow-lg' 
            : 'bg-gray-300 text-gray-500 cursor-not-allowed'"
          :disabled="!canCalculate"
        >
          <i class="fas fa-calculator mr-2"></i>
          {{ canCalculate ? '计算诉讼费' : '请完善计算参数' }}
        </button>

        <!-- 计算结果 -->
        <div v-if="calculationResult" class="mt-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-md font-semibold flex items-center">
              <i class="fas fa-calculator mr-2 text-blue-600"></i>
              计算结果
            </h3>
            <button 
              @click="saveCalculation"
              class="px-3 py-1 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors flex items-center"
            >
              <i class="fas fa-save mr-1"></i>
              保存记录
            </button>
          </div>
          
          <!-- 案件信息概览 -->
          <div class="mb-4 p-3 bg-gray-50 rounded-lg">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-2 text-sm">
              <div class="flex items-center">
                <i class="fas fa-tag mr-2 text-gray-500"></i>
                <span class="text-gray-600">案件类型：</span>
                <span class="font-medium ml-1">{{ calculationResult.caseTypeLabel }}</span>
              </div>
              <div class="flex items-center">
                <i class="fas fa-cogs mr-2 text-gray-500"></i>
                <span class="text-gray-600">审理程序：</span>
                <span class="font-medium ml-1">{{ calculationResult.procedureLabel }}</span>
              </div>
              <div class="flex items-center">
                <i class="fas fa-layer-group mr-2 text-gray-500"></i>
                <span class="text-gray-600">审级：</span>
                <span class="font-medium ml-1">{{ calculationResult.courtLevelLabel }}</span>
              </div>
            </div>
          </div>
          
          <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 space-y-4 border border-blue-100">
            <!-- 费用明细 -->
            <div v-if="calculationResult.breakdown && calculationResult.breakdown.length > 0" class="bg-white rounded-lg p-4 shadow-sm">
              <h4 class="text-sm font-semibold text-gray-800 mb-3 flex items-center">
                <i class="fas fa-list-ul mr-2"></i>
                费用明细
              </h4>
              <div class="space-y-2">
                <div 
                  v-for="(item, index) in calculationResult.breakdown" 
                  :key="index"
                  class="flex justify-between items-center py-2 border-b border-gray-100 last:border-b-0"
                >
                  <div class="flex-1">
                    <span class="text-sm text-gray-700">{{ item.item }}</span>
                    <p v-if="item.note" class="text-xs text-gray-500 mt-0.5">{{ item.note }}</p>
                  </div>
                  <span class="text-sm font-medium text-blue-600">¥{{ item.amount.toFixed(2) }}</span>
                </div>
              </div>
            </div>
            
            <!-- 费用汇总 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="bg-white rounded-lg p-3 shadow-sm">
                <div class="flex justify-between items-center">
                  <span class="text-sm font-medium text-gray-700">案件受理费：</span>
                  <span class="text-blue-600 font-semibold">¥{{ calculationResult.acceptanceFee }}</span>
                </div>
              </div>
              <div class="bg-white rounded-lg p-3 shadow-sm">
                <div class="flex justify-between items-center">
              <span class="text-sm font-medium text-gray-700">其他费用：</span>
              <span class="text-gray-600">¥{{ calculationResult.otherFees }}</span>
                </div>
              </div>
            </div>
            
            <!-- 总计 -->
            <div class="bg-white rounded-lg p-4 shadow-sm border-l-4 border-blue-500">
              <div class="flex justify-between items-center">
                <span class="text-base font-semibold text-gray-800">总计费用：</span>
                <span class="text-2xl font-bold text-blue-600">¥{{ calculationResult.totalFee }}</span>
              </div>
            </div>
            
            <!-- 计算说明 -->
            <div class="bg-yellow-50 rounded-lg p-3 border border-yellow-200">
              <div class="flex items-start">
                <i class="fas fa-info-circle text-yellow-600 mr-2 mt-0.5"></i>
                <div class="text-xs text-yellow-800">
                  <p class="font-medium">{{ calculationResult.notes }}</p>
                  <p class="mt-1">{{ calculationResult.details }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 计算历史记录 -->
        <div v-if="calculationHistory.length > 0" class="mt-6">
          <h3 class="text-md font-semibold mb-3 flex items-center">
            <i class="fas fa-history mr-2"></i>
            计算历史
            <button 
              @click="clearHistory"
              class="ml-auto text-sm text-red-600 hover:text-red-700"
            >
              清空记录
            </button>
          </h3>
          <div class="space-y-2 max-h-40 overflow-y-auto">
            <div 
              v-for="(record, index) in calculationHistory.slice().reverse()" 
              :key="index"
              class="bg-gray-50 rounded-lg p-3 text-sm cursor-pointer hover:bg-gray-100"
              @click="loadHistoryRecord(record)"
            >
              <div class="flex justify-between items-center">
                <div class="flex-1">
                  <div class="font-medium">
                    {{ getCaseTypeName(record.caseType, record.civilSubType || record.applicationSubType) }}
                  </div>
                  <div class="text-xs text-gray-600 mt-1" v-if="record.amount && record.amount > 0">
                    标的额：{{ formatAmount(record.amount) }}
                  </div>
                </div>
                <span class="text-blue-600 font-medium">¥{{ record.totalFee }}</span>
              </div>
              <div class="text-xs text-gray-500 mt-2 flex justify-between">
                <span>{{ record.timestamp }}</span>
                <span>{{ record.procedureType === 'simple' ? '简易程序' : record.procedureType === 'summary' ? '小额诉讼' : '普通程序' }} | {{ record.courtLevel === 'second' ? '二审' : '一审' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'LitigationFeeCalculator',
  setup() {
    const caseType = ref('')
    const claimAmount = ref('')
    const procedureType = ref('ordinary')
    const courtLevel = ref('first')
    // 删除具体案件类型字段
    const calculationResult = ref(null)
    const calculationHistory = ref([])

    // 案件类型选项配置
    const caseTypeOptions = ref([
      {
        value: 'civil',
        label: '民事案件',
        description: '民事纠纷案件',
        icon: 'fas fa-handshake'
      },
      {
        value: 'administrative',
        label: '行政案件',
        description: '行政诉讼案件',
        icon: 'fas fa-university'
      },
      {
        value: 'criminal-civil',
        label: '刑事附带民事案件',
        description: '刑事案件中的民事赔偿',
        icon: 'fas fa-balance-scale'
      },
      {
        value: 'execution',
        label: '执行案件',
        description: '强制执行案件',
        icon: 'fas fa-gavel'
      },
      {
        value: 'application',
        label: '申请类案件',
        description: '各类申请事项',
        icon: 'fas fa-file-alt'
      }
    ])

    // 从本地存储加载历史记录
    onMounted(() => {
      const saved = localStorage.getItem('litigationFeeHistory')
      if (saved) {
        calculationHistory.value = JSON.parse(saved)
      }
    })

    // 获取案件类型标签
    const getCaseTypeLabel = (type) => {
      const option = caseTypeOptions.value.find(opt => opt.value === type)
      return option ? option.label : type
    }

    // 获取申请类型信息
    const getApplicationTypeInfo = (subType) => {
      const infoMap = {
        'payment-order': '申请支付令：每件300元',
        'bankruptcy': '破产申请：每件1000元',
        'public-notice': '公示催告：每件100元',
        'arbitration-execution': '仲裁裁决执行申请：每件50元',
        'property-preservation': '财产保全申请：每件30元',
        'evidence-preservation': '证据保全申请：每件25元',
        'court-authentication': '司法确认申请：每件80元',
        'other': '其他申请：每件50元'
      }
      return infoMap[subType] || '申请类案件固定收费'
    }

    // 是否可以使用小额诉讼程序
    const canUseSummaryProcedure = computed(() => {
      return caseType.value === 'civil' && civilSubType.value === 'property' && 
             claimAmount.value > 0 && claimAmount.value <= 100000
    })

    // 简化的表单验证逻辑
    const canCalculate = computed(() => {
      // 基本要求：案件类型、审理程序、审级
      return caseType.value && procedureType.value && courtLevel.value
    })

    // 验证金额是否有效
    const isValidAmount = (amount) => {
      return amount && !isNaN(amount) && amount > 0 && amount <= 999999999999 // 最大支持万亿级别
    }

    // 获取验证错误信息
    const getValidationErrors = () => {
      const errors = []
      
      if (!caseType.value) {
        errors.push('请选择案件类型')
      }
      
      if (!procedureType.value) {
        errors.push('请选择审理程序')
      }
      
      if (!courtLevel.value) {
        errors.push('请选择审级')
      }
      
      return errors
    }

    // 案件类型改变时的处理
    const onCaseTypeChange = () => {
      calculationResult.value = null
    }

    // 格式化金额显示
    const formatAmount = (amount) => {
      if (!amount || amount === '') return '0.00元'
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount).replace('CN¥', '') + '元'
    }

    // 获取案件类型名称
    const getCaseTypeName = (type, subType = '') => {
      const typeMap = {
        'civil': '民事案件',
        'administrative': '行政案件',
        'criminal-civil': '刑事附带民事案件',
        'execution': '执行案件',
        'application': '申请类案件'
      }
      
      const subTypeMap = {
        'property': '财产案件',
        'non-property': '非财产案件',
        'payment-order': '申请支付令',
        'bankruptcy': '破产申请',
        'public-notice': '公示催告',
        'arbitration-execution': '仲裁裁决执行申请',
        'property-preservation': '财产保全申请',
        'evidence-preservation': '证据保全申请',
        'court-authentication': '司法确认申请',
        'other': '其他申请'
      }
      
      let name = typeMap[type] || type
      if (subType && subTypeMap[subType]) {
        name += `（${subTypeMap[subType]}）`
      }
      
      return name
    }

    // 重构后的诉讼费计算逻辑
    const calculateFee = () => {
      if (!canCalculate.value) return
      
      const amount = parseFloat(claimAmount.value) || 0
      let acceptanceFee = 0
      let details = ''
      let otherFees = 0
      let feeBreakdown = []
      
      // 根据案件类型计算基础费用
      switch (caseType.value) {
        case 'civil':
          const civilResult = calculateCivilCaseFee(amount)
          acceptanceFee = civilResult.fee
          details = civilResult.details
          feeBreakdown = civilResult.breakdown
          break
          
        case 'administrative':
          acceptanceFee = 100
          details = '行政案件固定收费标准'
          feeBreakdown = [{ item: '行政案件受理费', amount: 100, note: '固定收费' }]
          break
          
        case 'criminal-civil':
          const criminalCivilResult = calculateCriminalCivilCaseFee(amount)
          acceptanceFee = criminalCivilResult.fee
          details = criminalCivilResult.details
          feeBreakdown = criminalCivilResult.breakdown
          break
          
        case 'execution':
          const executionResult = calculateExecutionCaseFee(amount)
          acceptanceFee = executionResult.fee
          details = executionResult.details
          feeBreakdown = executionResult.breakdown
          break
          
        case 'application':
          const applicationResult = calculateApplicationCaseFee()
          acceptanceFee = applicationResult.fee
          details = applicationResult.details
          feeBreakdown = applicationResult.breakdown
          break
      }

      // 应用程序类型调整
      const procedureResult = applyProcedureAdjustment(acceptanceFee, details, amount)
      acceptanceFee = procedureResult.fee
      details = procedureResult.details
      
      // 审级调整
      if (courtLevel.value === 'second') {
        const originalFee = acceptanceFee
        acceptanceFee = acceptanceFee * 1.5
        details += `，二审按一审标准的1.5倍收费（${originalFee.toFixed(2)} × 1.5）`
      }

      const totalFee = acceptanceFee + otherFees

      calculationResult.value = {
        acceptanceFee: acceptanceFee.toFixed(2),
        otherFees: otherFees.toFixed(2),
        totalFee: totalFee.toFixed(2),
        notes: '以上费用根据《诉讼费用交纳办法》计算，仅供参考',
        details: details,
        breakdown: feeBreakdown,
        caseTypeLabel: getCaseTypeLabel(caseType.value),
        procedureLabel: getProcedureLabel(),
        courtLevelLabel: courtLevel.value === 'first' ? '一审' : '二审'
      }
    }

    // 计算民事案件费用
    const calculateCivilCaseFee = (amount) => {
      if (civilSubType.value === 'property') {
        return calculatePropertyCaseFee(amount)
      } else if (civilSubType.value === 'non-property') {
        return calculateNonPropertyCaseFee()
      }
      return { fee: 0, details: '', breakdown: [] }
    }

    // 计算刑事附带民事案件费用
    const calculateCriminalCivilCaseFee = (amount) => {
      const result = calculatePropertyCaseFee(amount)
      result.details = result.details + '（刑事附带民事案件参照民事财产案件标准）'
      result.breakdown = result.breakdown.map(item => ({
        ...item,
        note: (item.note || '') + ' (刑事附带民事)'
      }))
      return result
    }

    // 计算执行案件费用
    const calculateExecutionCaseFee = (amount) => {
      const fee = calculateExecutionFee(amount)
      const details = getExecutionFeeDetails(amount)
      const breakdown = getExecutionFeeBreakdown(amount, fee)
      return { fee, details, breakdown }
    }

    // 计算申请类案件费用
    const calculateApplicationCaseFee = () => {
      const fee = calculateApplicationFee(applicationSubType.value)
      const details = getApplicationFeeDetails(applicationSubType.value)
      const breakdown = [{
        item: getApplicationTypeName(applicationSubType.value),
        amount: fee,
        note: '固定收费标准'
      }]
      return { fee, details, breakdown }
    }

    // 获取程序类型标签
    const getProcedureLabel = () => {
      const labels = {
        'ordinary': '普通程序',
        'simple': '简易程序',
        'summary': '小额诉讼程序'
      }
      return labels[procedureType.value] || '普通程序'
    }

    // 获取申请类型名称
    const getApplicationTypeName = (subType) => {
      const nameMap = {
        'payment-order': '申请支付令',
        'bankruptcy': '破产申请',
        'public-notice': '公示催告',
        'arbitration-execution': '仲裁裁决执行申请',
        'property-preservation': '财产保全申请',
        'evidence-preservation': '证据保全申请',
        'court-authentication': '司法确认申请',
        'other': '其他申请'
      }
      return nameMap[subType] || '申请类案件'
    }

    // 计算财产案件费用（返回结构化数据）
    const calculatePropertyCaseFee = (amount) => {
      let fee = 0
      let details = ''
      let breakdown = []
      
      if (amount <= 10000) {
        fee = 50
        details = '适用最低收费标准50元'
        breakdown = [{ item: '财产案件受理费', amount: 50, note: '1万元以下固定收费' }]
      } else if (amount <= 100000) {
        fee = 50 + (amount - 10000) * 0.025
        details = '超过1万元至10万元部分，按2.5%交纳'
        breakdown = [
          { item: '基础费用', amount: 50, note: '1万元以下部分' },
          { item: '超额费用', amount: (amount - 10000) * 0.025, note: `${((amount - 10000)/10000).toFixed(1)}万元 × 2.5%` }
        ]
      } else if (amount <= 200000) {
        const baseFee = 2300
        const additionalFee = (amount - 100000) * 0.02
        fee = baseFee + additionalFee
        details = '超过10万元至20万元部分，按2%交纳'
        breakdown = [
          { item: '10万元以下费用', amount: 2300, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 100000)/10000).toFixed(1)}万元 × 2%` }
        ]
      } else if (amount <= 500000) {
        const baseFee = 4300
        const additionalFee = (amount - 200000) * 0.015
        fee = baseFee + additionalFee
        details = '超过20万元至50万元部分，按1.5%交纳'
        breakdown = [
          { item: '20万元以下费用', amount: 4300, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 200000)/10000).toFixed(1)}万元 × 1.5%` }
        ]
      } else if (amount <= 1000000) {
        const baseFee = 8800
        const additionalFee = (amount - 500000) * 0.01
        fee = baseFee + additionalFee
        details = '超过50万元至100万元部分，按1%交纳'
        breakdown = [
          { item: '50万元以下费用', amount: 8800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 500000)/10000).toFixed(1)}万元 × 1%` }
        ]
      } else if (amount <= 2000000) {
        const baseFee = 13800
        const additionalFee = (amount - 1000000) * 0.009
        fee = baseFee + additionalFee
        details = '超过100万元至200万元部分，按0.9%交纳'
        breakdown = [
          { item: '100万元以下费用', amount: 13800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 1000000)/10000).toFixed(1)}万元 × 0.9%` }
        ]
      } else if (amount <= 5000000) {
        const baseFee = 22800
        const additionalFee = (amount - 2000000) * 0.008
        fee = baseFee + additionalFee
        details = '超过200万元至500万元部分，按0.8%交纳'
        breakdown = [
          { item: '200万元以下费用', amount: 22800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 2000000)/10000).toFixed(1)}万元 × 0.8%` }
        ]
      } else if (amount <= 10000000) {
        const baseFee = 46800
        const additionalFee = (amount - 5000000) * 0.007
        fee = baseFee + additionalFee
        details = '超过500万元至1000万元部分，按0.7%交纳'
        breakdown = [
          { item: '500万元以下费用', amount: 46800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 5000000)/10000).toFixed(1)}万元 × 0.7%` }
        ]
      } else if (amount <= 20000000) {
        const baseFee = 81800
        const additionalFee = (amount - 10000000) * 0.006
        fee = baseFee + additionalFee
        details = '超过1000万元至2000万元部分，按0.6%交纳'
        breakdown = [
          { item: '1000万元以下费用', amount: 81800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 10000000)/10000).toFixed(1)}万元 × 0.6%` }
        ]
      } else {
        const baseFee = 141800
        const additionalFee = (amount - 20000000) * 0.005
        fee = baseFee + additionalFee
        details = '超过2000万元部分，按0.5%交纳'
        breakdown = [
          { item: '2000万元以下费用', amount: 141800, note: '累计基础费用' },
          { item: '超额费用', amount: additionalFee, note: `${((amount - 20000000)/10000).toFixed(1)}万元 × 0.5%` }
        ]
      }
      
      return { fee, details, breakdown }
    }

    // 获取财产案件费用详情
    const getPropertyCaseDetails = (amount) => {
      if (amount <= 10000) {
        return '适用最低收费标准50元'
      } else if (amount <= 100000) {
        return '超过1万元至10万元部分，按2.5%交纳'
      } else if (amount <= 200000) {
        return '超过10万元至20万元部分，按2%交纳'
      } else if (amount <= 500000) {
        return '超过20万元至50万元部分，按1.5%交纳'
      } else if (amount <= 1000000) {
        return '超过50万元至100万元部分，按1%交纳'
      } else if (amount <= 2000000) {
        return '超过100万元至200万元部分，按0.9%交纳'
      } else if (amount <= 5000000) {
        return '超过200万元至500万元部分，按0.8%交纳'
      } else if (amount <= 10000000) {
        return '超过500万元至1000万元部分，按0.7%交纳'
      } else if (amount <= 20000000) {
        return '超过1000万元至2000万元部分，按0.6%交纳'
      } else {
        return '超过2000万元部分，按0.5%交纳'
      }
    }

    // 计算非财产案件费用
    const calculateNonPropertyCaseFee = () => {
      const fee = 300
      const details = '非财产案件固定收费标准'
      const breakdown = [{ item: '非财产案件受理费', amount: 300, note: '固定收费标准' }]
      return { fee, details, breakdown }
    }

    // 获取执行案件费用明细
    const getExecutionFeeBreakdown = (amount, fee) => {
      const breakdown = []
      
      if (amount <= 10000) {
        breakdown.push({ item: '执行案件受理费', amount: 50, note: '1万元以下固定收费' })
      } else {
        let remaining = amount
        let currentFee = 0
        
        if (remaining > 10000) {
          const portion = Math.min(remaining - 10000, 490000)
          currentFee = portion * 0.015
          breakdown.push({ 
            item: '1万元-50万元部分', 
            amount: currentFee + 50, 
            note: `50元 + ${(portion/10000).toFixed(1)}万元 × 1.5%` 
          })
          remaining -= portion
        }
        
        if (remaining > 500000) {
          const portion = Math.min(remaining - 500000, 4500000)
          currentFee = portion * 0.01
          breakdown.push({ 
            item: '50万元-500万元部分', 
            amount: currentFee, 
            note: `${(portion/10000).toFixed(1)}万元 × 1%` 
          })
          remaining -= portion
        }
        
        if (remaining > 5000000) {
          const portion = Math.min(remaining - 5000000, 5000000)
          currentFee = portion * 0.005
          breakdown.push({ 
            item: '500万元-1000万元部分', 
            amount: currentFee, 
            note: `${(portion/10000).toFixed(1)}万元 × 0.5%` 
          })
          remaining -= portion
        }
        
        if (remaining > 10000000) {
          currentFee = (remaining - 10000000) * 0.001
          breakdown.push({ 
            item: '1000万元以上部分', 
            amount: currentFee, 
            note: `${((remaining - 10000000)/10000).toFixed(1)}万元 × 0.1%` 
          })
        }
      }
      
      return breakdown
    }

    // 计算执行案件费用
    const calculateExecutionFee = (amount) => {
      if (amount <= 10000) {
        return 50
      } else if (amount <= 500000) {
        return 50 + (amount - 10000) * 0.015
      } else if (amount <= 5000000) {
        return 7400 + (amount - 500000) * 0.01
      } else if (amount <= 10000000) {
        return 52400 + (amount - 5000000) * 0.005
      } else {
        return 77400 + (amount - 10000000) * 0.001
      }
    }

    // 获取执行费用详情
    const getExecutionFeeDetails = (amount) => {
      if (amount <= 10000) {
        return '执行金额1万元以下，每件50元'
      } else if (amount <= 500000) {
        return '执行金额超过1万元至50万元部分，按1.5%交纳'
      } else if (amount <= 5000000) {
        return '执行金额超过50万元至500万元部分，按1%交纳'
      } else if (amount <= 10000000) {
        return '执行金额超过500万元至1000万元部分，按0.5%交纳'
      } else {
        return '执行金额超过1000万元部分，按0.1%交纳'
      }
    }

    // 计算申请类案件费用
    const calculateApplicationFee = (subType) => {
      const feeMap = {
        'payment-order': 300,        // 申请支付令
        'bankruptcy': 1000,          // 破产申请
        'public-notice': 100,        // 公示催告
        'arbitration-execution': 50, // 仲裁裁决执行申请
        'property-preservation': 30, // 财产保全申请
        'evidence-preservation': 25, // 证据保全申请
        'court-authentication': 80, // 司法确认申请
        'other': 50                 // 其他申请
      }
      return feeMap[subType] || 50
    }

    // 获取申请类案件费用详情
    const getApplicationFeeDetails = (subType) => {
      const detailMap = {
        'payment-order': '申请支付令，每件300元',
        'bankruptcy': '破产申请，每件1000元',
        'public-notice': '公示催告，每件100元',
        'arbitration-execution': '仲裁裁决执行申请，每件50元',
        'property-preservation': '财产保全申请，每件30元',
        'evidence-preservation': '证据保全申请，每件25元',
        'court-authentication': '司法确认申请，每件80元',
        'other': '其他申请，每件50元'
      }
      return detailMap[subType] || '申请类案件固定收费'
    }

    // 应用程序类型调整
    const applyProcedureAdjustment = (originalFee, originalDetails, amount) => {
      let fee = originalFee
      let details = originalDetails
      
      if (procedureType.value === 'simple') {
        fee = originalFee * 0.5
        details += '，简易程序减半收费'
      } else if (procedureType.value === 'summary') {
        // 小额诉讼程序
        if (amount <= 100000) {
          const adjustedFee = Math.min(originalFee, 500)
          fee = adjustedFee
          details += '，小额诉讼程序最高收费500元'
        } else {
          details += '，超出小额诉讼范围，按普通程序收费'
        }
      }
      
      return { fee, details }
    }

    // 保存计算记录
    const saveCalculation = () => {
      if (!calculationResult.value) return
      
      const record = {
        timestamp: new Date().toLocaleString('zh-CN'),
        amount: claimAmount.value,
        caseType: caseType.value,
        civilSubType: civilSubType.value,
        applicationSubType: applicationSubType.value,
        procedureType: procedureType.value,
        courtLevel: courtLevel.value,
        totalFee: calculationResult.value.totalFee
      }
      
      calculationHistory.value.unshift(record)
      
      // 限制历史记录数量
      if (calculationHistory.value.length > 20) {
        calculationHistory.value = calculationHistory.value.slice(0, 20)
      }
      
      // 保存到本地存储
      localStorage.setItem('litigationFeeHistory', JSON.stringify(calculationHistory.value))
    }

    // 清空历史记录
    const clearHistory = () => {
      calculationHistory.value = []
      localStorage.removeItem('litigationFeeHistory')
    }

    // 加载历史记录
    const loadHistoryRecord = (record) => {
      claimAmount.value = record.amount || ''
      caseType.value = record.caseType || ''
      civilSubType.value = record.civilSubType || ''
      applicationSubType.value = record.applicationSubType || ''
      procedureType.value = record.procedureType || 'ordinary'
      courtLevel.value = record.courtLevel || 'first'
      
      // 自动重新计算
      if (canCalculate.value) {
        calculateFee()
      }
    }

    return {
      caseType,
      claimAmount,
      procedureType,
      courtLevel,
      civilSubType,
      applicationSubType,
      calculationResult,
      calculationHistory,
      caseTypeOptions,
      canCalculate,
      canUseSummaryProcedure,
      isValidAmount,
      getValidationErrors,
      onCaseTypeChange,
      formatAmount,
      getCaseTypeName,
      getCaseTypeLabel,
      getApplicationTypeInfo,
      getProcedureLabel,
      getApplicationTypeName,
      calculateFee,
      saveCalculation,
      clearHistory,
      loadHistoryRecord
    }
  }
}
</script>
